package cn.dansj.socket;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import cn.dansj.common.utils.json.DictMap;
import cn.dansj.enums.GlobalEnv;
import cn.dansj.common.context.ApplicationContextProvider;
import cn.dansj.common.redis.RedisUtils;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import jakarta.websocket.server.ServerEndpointConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@ServerEndpoint(value = "/getQrCode/{sid}", configurator = WebSocketServer.class)
@Component
//Cannot deploy POJO class [cn.dansj.socket.WebSocketServer] as it is not annotated with @ServerEndpoint
public class WebSocketServer extends ServerEndpointConfig.Configurator {
    private static final RedisUtils redisUtils = ApplicationContextProvider.getBean(RedisUtils.class);
    static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收sid
    private String sid = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) throws IOException {
        this.session = session;
        this.sid = sid;
        this.session.setMaxIdleTimeout(10 * 60 * 1000);
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新的扫码登录请求开始:" + sid + ",当前扫码登录人数为" + getOnlineCount());
        checkQrTokenExist();
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() throws IOException {
        this.session.close();
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("扫码结束！当前扫码登录人数为" + getOnlineCount());
        clearQrToken();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        try {
            JSONObject clientMessage = DictMap.parseObject(message);
            if ("expired".equals(clientMessage.getString("type"))) clearQrToken();
        } catch (Exception e) {
            log.error("处理客户端消息异常", e);
            clearQrToken();
        }
        log.info("收到来自窗口{}的信息:{}", sid, message);
    }

    public void clearQrToken() {
        redisUtils.delete(GlobalEnv.QRCodePrefix + sid);
    }

    public void checkQrTokenExist() throws IOException {
        if (!redisUtils.hasKey(GlobalEnv.QRCodePrefix + sid)) {
            sendMessage("token不存在");
            session.close();
        }
    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        session.close();
        clearQrToken();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        if (this.session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) {
        // log.info("推送消息到窗口" + sid + "，推送内容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if (sid == null) {
                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException ignored) {
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        super.modifyHandshake(sec, request, response);
        final Map<String, Object> userProperties = sec.getUserProperties();
        userProperties.put("origin", String.join(",", request.getHeaders().get("origin")));
    }
}